package router

import (
	"os"
	"path/filepath"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/itstonight/ziyue/controller"
	"github.com/itstonight/ziyue/controller/auth"
)

// SetupRouter 初始化路由
// func SetupRouter(router *gin.Engine) {
// 	api := router.Group("/api")

// 	// 认证相关路由
// 	auth := api.Group("/auth")
// 	{
// 		auth.POST("/register", controller.Register)
// 		auth.POST("/login", controller.Login)
// 		// 退出登录需要验证token
// 		auth.POST("/logout", middleware.AuthMiddleware(), controller.Logout)
// 		// 获取用户信息
// 		auth.GET("/userinfo", middleware.AuthMiddleware(), controller.GetUserInfo)
// 	}

// 	// 需要认证的路由组
// 	authenticated := api.Group("/")
// 	authenticated.Use(middleware.AuthMiddleware())
// 	{
// 		// 文档相关路由
// 		docs := authenticated.Group("/documents")
// 		{
// 			docs.GET("", controller.ListDocuments)
// 			docs.GET("/:id", controller.GetDocument)
// 			docs.PUT("/:id", controller.UpdateDocument)
// 			// 添加锁定和解锁文档的路由
// 			docs.POST("/:id/lock", controller.LockDocument)
// 			docs.POST("/:id/unlock", controller.UnlockDocument)
// 		}
// 	}
// }

func SetupRouter(engine *gin.Engine) {
	mw := cors.New(cors.Config{
		AllowOrigins:     []string{"http://localhost:5173"},
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Content-Type", "Authorization"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	})

	engine.Use(mw)

	api := engine.Group("/api")

	// 认证相关路由
	{
		r := api.Group("/auth")

		r.POST("/login", controller.Login)
		r.POST("/register", controller.Register)
	}

	{
		r := api.Group("/users").Use(auth.Middleware)

		r.GET("/me", controller.CurrentUser)
	}

	{
		r := api.Group("/documents", auth.Middleware)
		r.GET("/", controller.ListDocuments)
		r.GET("/:id", controller.GetDocument)
		r.PUT("/:id", controller.UpdateDocument)
		r.POST("/:id/lock", controller.LockDocument)
	}

	// 提供静态文件服务
	// 使用中间件提供静态文件服务
	engine.Use(func(c *gin.Context) {
		filePath := filepath.Join("./dist", c.Request.URL.Path)
		if _, err := os.Stat(filePath); err == nil {
			c.File(filePath)
			c.Abort()
			return
		}
		c.Next()
	})

	// 当没有任何路由匹配时，返回 index.html
	engine.NoRoute(func(c *gin.Context) {
		c.File("./dist/index.html")
	})
}
